using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.IO;
using System.IO.IsolatedStorage;
using System.Xml.Serialization;

namespace SharePointSearchBench
{
    /// <summary>
    /// Represents the list of recent files used in the application.
    /// </summary>
    public class RecentFileCollection : ObservableCollection<RecentFile>
    {
        const string Filename = "RecentFiles.xml";
        const int MaxItemCount = 7;

        /// <summary>
        /// Creates a new instance of the class.
        /// </summary>
        public RecentFileCollection()
        {
            this.Load();
        }

        void Load()
        {
            IsolatedStorageFileStream stream = null;
            IsolatedStorageFile file = null;
            try
            {
                file = IsolatedStorageFile.GetUserStoreForAssembly();
                string[] files = file.GetFileNames(RecentFileCollection.Filename);
                if(files.Length > 0)
                {
                    stream = new IsolatedStorageFileStream(RecentFileCollection.Filename, FileMode.Open, FileAccess.Read, file);
                    XmlSerializer serializer = new XmlSerializer(typeof(Collection<RecentFile>));
                    Collection<RecentFile> items = serializer.Deserialize(stream) as Collection<RecentFile>;

                    base.Clear();
                    foreach(RecentFile item in items)
                    {
                        base.Add(item);
                    }
                }

            }
            finally
            {
                if(stream != null)
                {
                    stream.Dispose();
                }
            }
        }

        /// <summary>
        /// Persists the list of files to disk.
        /// </summary>
        public void Save()
        {

            IsolatedStorageFileStream stream = null;
            IsolatedStorageFile file = null;
            try
            {
                file = IsolatedStorageFile.GetUserStoreForAssembly();
                XmlSerializer serializer = new XmlSerializer(typeof(Collection<RecentFile>));
                stream = new IsolatedStorageFileStream(RecentFileCollection.Filename, FileMode.Create, FileAccess.Write, file);
                serializer.Serialize(stream, this);
            }
            finally
            {
                if(stream != null)
                {
                    stream.Dispose();
                }
            }
        }

        protected override void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            base.OnCollectionChanged(e);

            if(this.Count > MaxItemCount)
            {
                this.RemoveAt(0);
            }
        }
    }
}
